package cn.lzx.user.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token = request.getHeader("token");
        if (token!=null) {
            Object obj = redisTemplate.opsForValue().get(token);
            if (obj != null) {
                //刷新登录过期时间
                redisTemplate.opsForValue().set(token,obj,30, TimeUnit.MINUTES);
                return true;
            }else {
                //没有登录过  or 过期了 跳转登录页面
                //设置字符集
                response.setCharacterEncoding("UTF-8");
                //告诉浏览器我要给你响应一个json数据，用Utf-8编码
                response.setContentType("application/json;charset=UTF-8");
                //这是一个json格式的数据 表示 success:false msg:noLogin
                response.getWriter().write("{\"success\":false,\"msg\":\"noLogin\"}");
                return false;
            }
        }
        return false;
    }


}
